import { Inject, Injectable, InjectionToken } from '@angular/core';

export interface IMapAPILoaderConfig {
  apiKey?: string;
  apiVersion?: string;
  urlPath?: string;
}
export const MAP_API_CONFIG = new InjectionToken<IMapAPILoaderConfig>('kylin-ngx-amap MAP_API_CONFIG');
@Injectable({
  providedIn: 'root'
})
export class AmapLoaderService {
  private _defaultUrl = 'https://webapi.amap.com/maps';
  private _defaultVersion = '1.4.15';
  private _config: IMapAPILoaderConfig;
  private _mapReady = false;
  constructor(@Inject(MAP_API_CONFIG) config: any) {
    this._config = config || {};
  }

  load = (): Promise<any> => {
    return new Promise((resolve, reject) => {
      if (this._mapReady) {
        resolve('ready');
      } else {
        window['AMapLoad'] = () => {
          this._mapReady = true;
          resolve('ready');
        }
        const url = `${this._config.urlPath || this._defaultUrl}?v=${this._config.apiVersion || this._defaultVersion}&key=${this._config.apiKey}&callback=AMapLoad`;
        const jsapi = document.createElement('script');
        jsapi['charset'] = 'utf-8';
        jsapi.src = url;
        jsapi.onerror = (error: Event) => { reject(error); };
        document.head.appendChild(jsapi);
      }
    })
  }
}
